package com.polarrose.wsf.validator;

import java.util.List;

public class LengthValidator implements Validator<Object>
{
	private int minLength = 0;
	private int maxLength = Integer.MAX_VALUE;

	public void validate(Object o)
        throws ValidatorException
    {
		if (o instanceof String) {
			String s = (String) o;
			if (s.length() < minLength || s.length() > maxLength) {
				throw new ValidatorException("the length is not within the acceptable range [" + minLength + "," + maxLength + "]");
			}
		} else if (o instanceof List) {
			List list = (List) o;
            if (list.size() < minLength || list.size() > maxLength) {
                throw new ValidatorException("the length is not within the acceptable range [" + minLength + "," + maxLength + "]");
            }
		}        
        throw new IllegalArgumentException("The LengthValidator only supports Strings and Lists.");
	}

	public void setMaxLength(String maxLength)
    {
		this.maxLength = Integer.parseInt(maxLength);
		if (this.maxLength < 0) {
			throw new IllegalArgumentException("Only positive integers are allowed as maxLength");
		}
	}

	public void setMinLength(String minLength)
    {
		this.minLength = Integer.parseInt(minLength);
		if (this.minLength < 0) {
			throw new IllegalArgumentException("Only positive integers are allowed as minLength");
		}
	}
}
